package com.project.service.dao.impl;

import com.project.service.bean.StudentBean;
import com.project.service.dao.IStudentDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl extends BaseDao implements IStudentDao {
    @Override
    public void add(StudentBean studentBean) {
        this.setConnection();

        try {
            ps = con.prepareStatement("insert into t_student(s_name,fk_classId) values(?,?)");
            ps.setObject(1,studentBean.getName());
            ps.setObject(2,studentBean.getClassBean().getId());

            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }
    }

    @Override
    public List<StudentBean> findAll() {
        List<StudentBean> list = new ArrayList<>();
        this.setConnection();

        try {
            ps = con.prepareStatement("select s.*,c.c_name  from t_student s,t_class c where s.fk_classId=c.pk_classId");

            rs = ps.executeQuery();

            while(rs.next()){
//                StudentBean student = new StudentBean();
//                student.setId(rs.getInt("pk_studentId"));
//                student.setName(rs.getString("s_name"));
//
//                ClassBean classBean = new ClassBean();
//                classBean.setName(rs.getString("c_name"));
//                student.setClassBean(classBean);
                StudentBean student = new StudentBean(rs.getInt("pk_studentId"),
                        rs.getString("s_name"),rs.getString("c_name"));

                list.add(student);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }

        return list;
    }

    public static void main(String[] args) {
        IStudentDao dao = new StudentDaoImpl();
        System.out.println(dao.findAll());
    }
}
